import { useRef, useLayoutEffect, useState, useEffect } from 'react'
import './face.scss'
import { Tag, Input, Button, message, notification, Select } from 'antd'
import { CloudUploadOutlined, AudioOutlined, PlayCircleOutlined } from '@ant-design/icons'
import dialogue from '@/utils/Ai'
import { useSelector } from 'react-redux'
import { getFace } from '@/api/face'
import createXfVoiceInstance from '../iFlytek/voiceToText/speak'
import ttsRecorder from '../iFlytek/textToVoice/voice.js'

function Face() {
  const xfVoiceRef = useRef<any>(null)
  const limit = useSelector((state: any) => state.user.userInfo.authority)
  const [api, contextHolder] = notification.useNotification()
  const [text, setText] = useState('')
  const videoElement = useRef<any>(null)
  const ttsWSRef = useRef<WebSocket | null>(null)
  const totalResRef = useRef<string>('')
  const [output, setOutput] = useState<string>('')
  const [topic, setTopic] = useState<string>('')
  const [start, setStart] = useState(false)
  const [isEnd, setIsEnd] = useState(true)
  const [faceData, setFaceData] = useState<any>({})
  const [isSendFace, setIsSendFace] = useState(false)
  const [isVoice, setIsVoice] = useState(false)
  const [fre, setFre] = useState(0)
  const [ttsInstance, setTtsInstance] = useState<any>(null)
  const [listenEnd, setListenEnd] = useState(false)

  let timer: any = null
  const [videoScore, setVideoScore] = useState({
    face: 60,
    clothes: 60,
  })
  const [videoTotalPoint, setVideoTotalPoint] = useState({
    face: 80,
    clothes: 80,
  })
  const [numProblem, setNumProblem] = useState(2)

  // 将json数据转换为formData
  const jsonToFormData = (json: any) => {
    const formData = new FormData()
    for (const key in json) {
      if (Array.isArray(json[key])) {
        json[key].forEach((item: any) => formData.append(key, item))
      } else {
        formData.append(key, json[key])
      }
    }
    return formData
  }

  // 开启摄像头
  const startCamera = async () => {
    try {
      const stream = await navigator.mediaDevices.getUserMedia({ video: true })
      if (videoElement.current) {
        videoElement.current.srcObject = stream
        // 启动人脸识别功能
        // setTimeout(() => {
        //   captureFrame() // 在相机启动后立即执行一次截图操作
        // }, 1000)
      }
    } catch (error) {
      console.error('Error accessing camera:', error)
    }
  }

  // 大模型回答内容合成为语音输出
  const handleSpeak = () => {
    let instance = ttsInstance

    if (!instance) {
      instance = new ttsRecorder()
      setTtsInstance(instance)
    }

    instance.setParams({
      text: output.replace(/<br\s*\/?>/g, ''),
    })

    if (listenEnd) {
      instance.start()
      message.success('开始播放！')
    } else {
      instance.stop()
      message.success('停止成功!')
    }

    setListenEnd(!listenEnd)
  }

  // 视频截图
  const captureFrame = async () => {
    const canvas = document.createElement('canvas')
    const video = videoElement.current
    if (video && video.videoWidth && video.videoHeight) {
      canvas.width = video.videoWidth
      canvas.height = video.videoHeight
      canvas.getContext('2d')!.drawImage(video, 0, 0, canvas.width, canvas.height)

      const blob = await new Promise<Blob | null>((resolve) => {
        canvas.toBlob((blob) => {
          resolve(blob)
        }, 'image/jpeg')
      })

      if (blob) {
        const file = new File([blob], 'captured_frame.jpg', { type: 'image/jpeg' })
        const res = await getFace(
          jsonToFormData({
            file: file,
          }),
        )
        setFaceData(res.data.data.fileList[0])
        setIsSendFace(true)
        // setTimeout(() => {
        //   captureFrame() // 继续执行下一次截图操作
        // }, 3000)
      } else {
        message.error('生成 Blob 失败！')
      }
    }
  }

  // 分析表情数据
  const getEmotionLabel = (label: number) => {
    switch (label) {
      case 0:
        return '其他(非人脸表情图片)'
      case 1:
        return '其他表情'
      case 2:
        return '喜悦'
      case 3:
        return '愤怒'
      case 4:
        return '悲伤'
      case 5:
        return '惊恐'
      case 6:
        return '厌恶'
      case 7:
        return '中性'
      default:
        return '数据未上传'
    }
  }

  // 关闭摄像头
  const stopCamera = () => {
    if (videoElement.current && videoElement.current.srcObject) {
      const stream = videoElement.current.srcObject as MediaStream
      const tracks = stream.getTracks()

      tracks.forEach((track) => {
        track.stop()
      })
    } else {
      console.warn('Video element or srcObject is null, unable to stop camera')
    }
  }

  // 点击开始面试的回调
  const startInterview = () => {
    if (topic) {
      setOutput('')
      setStart(true)
      getAiGrade()
    } else {
      message.error('请输入要面试的职位')
    }
  }

  useLayoutEffect(() => {
    if (start) {
      startCamera()
      timer = setInterval(() => {
        const num1 = getRandom()
        const num2 = getRandom()
        setVideoScore({ ...videoScore, face: num1, clothes: num2 })
        setVideoTotalPoint({
          ...videoScore,
          face: Math.ceil(60 + (num1 / 10) * 2),
          clothes: Math.ceil(60 + (num2 / 10) * 2),
        })
      }, 3000)
    }
    return () => {
      if (videoElement.current) {
        stopCamera()
      }
    }
  }, [start])

  useEffect(() => {
    xfVoiceRef.current = createXfVoiceInstance(handleTextChange)

    return () => {
      clearTimeout(timer)
      stopCamera()
      ttsWSRef.current?.close()
      xfVoiceRef.current.stop()
    }
  }, [])

  // 语音转文字功能
  const handleTextChange = (newText: any) => {
    setText(newText)
  }

  // 开启语言识别
  const speakStart = () => {
    if (isVoice) {
      xfVoiceRef.current.stop()
      navigator.mediaDevices.getUserMedia({ audio: false })
    } else {
      xfVoiceRef.current.start()
    }
    setIsVoice(!isVoice)
  }

  const handleMessageReceived = () => {
    setOutput(totalResRef.current)
  }

  // 是否结束
  const endofJudgment = (end: boolean) => {
    setIsEnd(end)
  }

  // 大模型分析
  const getAnalyze = () => {
    if (text) {
      if (isEnd) {
        const finallyText = `这是对一道${topic}面试题，${output}
        回答：${text}
        请打分，满分100分，如果回答的问题以实际不符则给0，回答的相符但不多给60以内，相差不大给60到80，很不错给80到100，详细分析回答并且告诉为什么这么评分。结果格式为：回答内容: ${text},回答评分，解析，答案`
        dialogue(finallyText, ttsWSRef, totalResRef, handleMessageReceived)
        setText('')
      } else {
        message.warning('请等待回答完毕！')
      }
    } else {
      message.warning('请输入回答！')
    }
  }

  // 大模型出题
  const getAiGrade = () => {
    const finallyTopic = `你是一名${topic}工作的面试官，请出一道面试题，不要问代码类型的，文字类型的，不用太长，问题只有一个。出题格式为：题目类型,题目内容`
    dialogue(finallyTopic, ttsWSRef, totalResRef, handleMessageReceived, endofJudgment)
  }

  useEffect(() => {
    if (fre === numProblem) {
      setOutput(`模拟面试结束`)
      openNotification()
      stopCamera()
      return
    }
    getAiGrade()
  }, [fre])

  const openNotification = () => {
    api['warning']({
      message: '通知',
      description: `模拟面试即将结束`,
      duration: 5,
      showProgress: true,
    })
    setTopic('')
    setTimeout(() => {
      setFre(0)
      setStart(false)
    }, 5000)
  }

  const getRandom = () => {
    return Math.floor(Math.random() * (90 - 60 + 1)) + 60
  }

  return (
    <>
      {limit.interview === 1 ? (
        <div className="Face">
          {contextHolder}
          {start ? (
            <>
              <div className="video-container">
                <video ref={videoElement} autoPlay></video>
                <div>
                  <div className="faceScore">
                    <p style={{ marginBottom: '10px' }}>
                      <span style={{ color: '#3fc1c9' }}>表情：</span>
                      <Tag color="success">{getEmotionLabel(faceData.label)}</Tag>
                      <Tag color="processing">
                        程度：{!isSendFace ? '无' : (faceData.rate * 100).toFixed(2) + '%'}
                      </Tag>
                    </p>
                    <p>
                      评分：<Tag color="success">{videoTotalPoint.face}分</Tag>
                    </p>
                  </div>
                  <div className="bearingScore">
                    <p style={{ marginBottom: '10px' }}>
                      <span style={{ color: '#3fc1c9' }}>仪表：</span>
                      <Tag color="success">得体</Tag>
                      <Tag color="processing">程度：{videoScore.clothes}%</Tag>
                    </p>
                    <p>
                      评分：<Tag color="success">{videoTotalPoint.clothes}分</Tag>
                    </p>
                  </div>
                </div>
              </div>
              <div className="content">
                <div className="dialogue">
                  <div dangerouslySetInnerHTML={{ __html: output }} className="question"></div>
                </div>
                <div className="content-input">
                  <Input
                    size="large"
                    allowClear
                    onChange={(e) => setText(e.target.value)}
                    onKeyDown={(e) => {
                      e.key === 'Enter' && getAnalyze()
                    }}
                    value={text}
                    prefix={
                      <AudioOutlined onClick={speakStart} style={{ color: 'rgba(0,0,0,.45)' }} />
                    }
                    suffix={
                      <CloudUploadOutlined
                        onClick={getAnalyze}
                        style={{ color: 'rgba(0,0,0,.45)' }}
                      />
                    }
                  />
                  <div className="con-inp"></div>
                </div>
                <div style={{ display: 'flex', alignItems: 'center' }}>
                  <Button
                    type="primary"
                    onClick={handleSpeak}
                    shape="circle"
                    style={{ marginRight: '10px' }}
                    icon={<PlayCircleOutlined />}
                  />
                  <Button
                    size="large"
                    onClick={() => {
                      setFre(fre + 1)
                    }}
                  >
                    下一题
                  </Button>
                </div>
              </div>
            </>
          ) : (
            <div className="beforStart">
              <Input
                onChange={(e) => setTopic(e.target.value)}
                onKeyDown={(e) => {
                  e.key === 'Enter' && startInterview()
                }}
                value={topic}
                size="large"
                className="topic"
                placeholder="请选择要面试的职位"
              ></Input>
              <div style={{ margin: '30px 0' }}>
                <span>题目数量：</span>
                <Select
                  defaultValue="2"
                  style={{ width: 120 }}
                  onChange={(val) => {
                    setNumProblem(Number(val))
                  }}
                  options={[
                    { value: '2', label: '2题' },
                    { value: '4', label: '4题' },
                    { value: '6', label: '6题' },
                    { value: '8', label: '8题' },
                    { value: '10', label: '10题' },
                  ]}
                ></Select>
              </div>
              <div onClick={startInterview} style={{ cursor: 'pointer' }} className="btn-conteiner">
                <div className="btn-content">
                  <span style={{ fontFamily: 'STKaiti' }} className="btn-title">
                    开始面试
                  </span>
                  <span className="icon-arrow">
                    <svg
                      width="66px"
                      height="43px"
                      viewBox="0 0 66 43"
                      version="1.1"
                      xmlns="http://www.w3.org/2000/svg"
                      xmlnsXlink="http://www.w3.org/1999/xlink"
                    >
                      <g id="arrow" stroke="none" strokeWidth="1" fill="none" fillRule="evenodd">
                        <path
                          id="arrow-icon-one"
                          d="M40.1543933,3.89485454 L43.9763149,0.139296592 C44.1708311,-0.0518420739 44.4826329,-0.0518571125 44.6771675,0.139262789 L65.6916134,20.7848311 C66.0855801,21.1718824 66.0911863,21.8050225 65.704135,22.1989893 C65.7000188,22.2031791 65.6958657,22.2073326 65.6916762,22.2114492 L44.677098,42.8607841 C44.4825957,43.0519059 44.1708242,43.0519358 43.9762853,42.8608513 L40.1545186,39.1069479 C39.9575152,38.9134427 39.9546793,38.5968729 40.1481845,38.3998695 C40.1502893,38.3977268 40.1524132,38.395603 40.1545562,38.3934985 L56.9937789,21.8567812 C57.1908028,21.6632968 57.193672,21.3467273 57.0001876,21.1497035 C56.9980647,21.1475418 56.9959223,21.1453995 56.9937605,21.1432767 L40.1545208,4.60825197 C39.9574869,4.41477773 39.9546013,4.09820839 40.1480756,3.90117456 C40.1501626,3.89904911 40.1522686,3.89694235 40.1543933,3.89485454 Z"
                          fill="#FFFFFF"
                        ></path>
                        <path
                          id="arrow-icon-two"
                          d="M20.1543933,3.89485454 L23.9763149,0.139296592 C24.1708311,-0.0518420739 24.4826329,-0.0518571125 24.6771675,0.139262789 L45.6916134,20.7848311 C46.0855801,21.1718824 46.0911863,21.8050225 45.704135,22.1989893 C45.7000188,22.2031791 45.6958657,22.2073326 45.6916762,22.2114492 L24.677098,42.8607841 C24.4825957,43.0519059 24.1708242,43.0519358 23.9762853,42.8608513 L20.1545186,39.1069479 C19.9575152,38.9134427 19.9546793,38.5968729 20.1481845,38.3998695 C20.1502893,38.3977268 20.1524132,38.395603 20.1545562,38.3934985 L36.9937789,21.8567812 C37.1908028,21.6632968 37.193672,21.3467273 37.0001876,21.1497035 C36.9980647,21.1475418 36.9959223,21.1453995 36.9937605,21.1432767 L20.1545208,4.60825197 C19.9574869,4.41477773 19.9546013,4.09820839 20.1480756,3.90117456 C20.1501626,3.89904911 20.1522686,3.89694235 20.1543933,3.89485454 Z"
                          fill="#FFFFFF"
                        ></path>
                        <path
                          id="arrow-icon-three"
                          d="M0.154393339,3.89485454 L3.97631488,0.139296592 C4.17083111,-0.0518420739 4.48263286,-0.0518571125 4.67716753,0.139262789 L25.6916134,20.7848311 C26.0855801,21.1718824 26.0911863,21.8050225 25.704135,22.1989893 C25.7000188,22.2031791 25.6958657,22.2073326 25.6916762,22.2114492 L4.67709797,42.8607841 C4.48259567,43.0519059 4.17082418,43.0519358 3.97628526,42.8608513 L0.154518591,39.1069479 C-0.0424848215,38.9134427 -0.0453206733,38.5968729 0.148184538,38.3998695 C0.150289256,38.3977268 0.152413239,38.395603 0.154556228,38.3934985 L16.9937789,21.8567812 C17.1908028,21.6632968 17.193672,21.3467273 17.0001876,21.1497035 C16.9980647,21.1475418 16.9959223,21.1453995 16.9937605,21.1432767 L0.15452076,4.60825197 C-0.0425130651,4.41477773 -0.0453986756,4.09820839 0.148075568,3.90117456 C0.150162624,3.89904911 0.152268631,3.89694235 0.154393339,3.89485454 Z"
                          fill="#FFFFFF"
                        ></path>
                      </g>
                    </svg>
                  </span>
                </div>
              </div>
            </div>
          )}
        </div>
      ) : (
        <div style={{ display: 'flex', justifyContent: 'center' }}>
          <div style={{ marginTop: '35vh', fontSize: '30px', color: 'red', fontWeight: '600' }}>
            没有使用权限
          </div>
        </div>
      )}
    </>
  )
}

export default Face
